//
//  CalculaterView.m
//  WWXELuShang
//
//  Created by 王涛 on 15/12/19.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "CalculaterView.h"
#import "CostModel.h"
@interface CalculaterView()
{
    Opration *oper;
    double a;
    BOOL flag;
}
@property (nonatomic, strong) UIButton *button10;
@end
@implementation CalculaterView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = kBackGroundColor;
        NSArray *array = @[@"加油费",@"保养费",@"过路费"];
        CGFloat width = self.frame.size.width / 2;
        CGFloat height = self.frame.size.height;
        CGFloat buttonwidth = kHeight / 13;//每个button大小
        for (int i = 0; i < 3; i ++) {
            UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
            button.frame = CGRectMake(i * buttonwidth + (width - buttonwidth * 3) / 4 * (i + 1), height / 45, buttonwidth, buttonwidth);
            [button setImage:[[UIImage imageNamed:[NSString stringWithFormat:@"Money%d.png",i]] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
            button.layer.borderColor = [kBackGroundColor CGColor];
            button.layer.borderWidth = 3;
            button.layer.masksToBounds = YES;
            button.userInteractionEnabled = YES;
            button.layer.cornerRadius = buttonwidth / 2;
            button.tag = 6000 * i + 600;
            [button addTarget:self action:@selector(change1:) forControlEvents:(UIControlEventTouchUpInside)];
            [self addSubview:button];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i * buttonwidth + (width - buttonwidth * 3) / 4 * (i + 1), height / 45 + buttonwidth, buttonwidth, buttonwidth / 2)];
            label.text = array[i];
            label.textAlignment = NSTextAlignmentCenter;
            label.font = [UIFont systemFontOfSize:12];
            label.tag = 6000 * i + 600;
            [self addSubview:label];
        }
        UILabel *moneyLabel = [[UILabel alloc] initWithFrame:(CGRectMake(kWidth / 2, height / 45 + buttonwidth / 2, kWidth / 2 - height / 45, buttonwidth / 2))];
        moneyLabel.textAlignment = NSTextAlignmentRight;
        moneyLabel.font = [UIFont boldSystemFontOfSize:20];
        moneyLabel.text = @"¥0.00";
        moneyLabel.tag = 1000;
        [self addSubview:moneyLabel];
        
        
        self.result = [[NSMutableString alloc] initWithFormat:@"0"];
        flag = YES;
        
        CGFloat cwidth = self.frame.size.width;
        CGFloat cheight = height - (height / 45 + buttonwidth) - buttonwidth / 2;
        
        for (int i = 0; i < 4; i ++) {
            for (int j = 0; j < 4; j ++) {
                if (i == 3 && j == 0) {
                    //这里是按键0的按钮
                    b = [UIButton buttonWithType:(UIButtonTypeSystem)];
                    b.frame = CGRectMake(j * (cwidth / 4), i * (cheight / 4) + ((height / 45 + buttonwidth) + buttonwidth / 2), cwidth / 2, cheight / 4);
                    b.backgroundColor = kBackGroundColor;
                    b.tag = (i + 1) * 10 + (j + 1);//设置tag值；
                    b.layer.borderWidth = 1;
                    b.layer.borderColor = [[UIColor lightGrayColor]CGColor];
                    [b setTitle:@"0" forState:(UIControlStateNormal)];
                    b.tintColor = [UIColor darkGrayColor];
                    b.titleLabel.font = [UIFont boldSystemFontOfSize:18];

                    [b addTarget:self action:@selector(number:) forControlEvents:(UIControlEventTouchDown)];
                    [self addSubview:b];
                    j ++;
                    continue;
                }
                //按钮的创建
                b = [UIButton buttonWithType:(UIButtonTypeSystem)];
                b.frame = CGRectMake(j * (cwidth / 4), i * (cheight / 4) + ((height / 45 + buttonwidth) + buttonwidth / 2), cwidth / 4, cheight / 4);
                b.backgroundColor = kBackGroundColor;
                b.layer.borderWidth = 1;
                b.tintColor = [UIColor darkGrayColor];
                b.titleLabel.font = [UIFont boldSystemFontOfSize:18];
                b.layer.borderColor = [[UIColor lightGrayColor] CGColor];
                b.tag = (i + 1) * 10 + (j + 1);
                [self addSubview:b];

                if (i >= 0 && j < 3 && i < 3) {
                    int num = (2 - i) * 3 + (j + 1);
                    NSString *s = [NSString stringWithFormat:@"%d",num];
                    [b setTitle:s forState:(UIControlStateNormal)];
                    [b addTarget:self action:@selector(number:) forControlEvents:UIControlEventTouchDown];
                }
                if (j == 3) {
                    b.tintColor = [UIColor redColor];
                    b.titleLabel.font = [UIFont boldSystemFontOfSize:20];
                }
                switch (b.tag) {
                    case 14:
                        [b setTitle:@"C" forState:UIControlStateNormal];
                        [b addTarget:self action:@selector(clearNum) forControlEvents:UIControlEventTouchDown];
                        break;
                    case 24:
                        [b setTitle:@"+" forState:UIControlStateNormal];
                        [b addTarget:self action:@selector(myOption:) forControlEvents:UIControlEventTouchDown];
                        break;
                    case 34:
                        [b setTitle:@"=" forState:UIControlStateNormal];
                        [b addTarget:self action:@selector(OptionResult) forControlEvents:UIControlEventTouchDown];
                        break;
                    case 43:
                        [b setTitle:@"." forState:UIControlStateNormal];
                        [b addTarget:self action:@selector(decimal:) forControlEvents:UIControlEventTouchDown];
                        break;
                    case 44:
                        [b setTitle:@"OK" forState:UIControlStateNormal];
                        [b addTarget:self action:@selector(saveMoney) forControlEvents:UIControlEventTouchDown];
                        break;
                    default:
                        break;
                }
            }
            
        }
        self.costModel = [[CostModel alloc] init];//初始化
        self.button10 = (UIButton *)[self viewWithTag:6000 * 2];
        [self.button10 addTarget:self action:@selector(change1:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return self;
}

-(void)decimal:(UIButton*)btn
{
    if ([self.result isEqualToString:@""])
    {
        [self.result appendString:@"0."];
    }
    else
    {
        [self.result appendString:@"."];
    }
    
}
//数字按钮的方法
-(void)number:(UIButton*)btn
{
    
    if ([self.result isEqualToString:@"0"]) {
        [self.result setString:@""];
        //如果初始状态为0，先置空一下，这样做的目的是为了在显示的时候不会开头还带着一个0
    }
    
    //这里的result是可变字符串，这样才可以对自己进行更改，添加
    [self.result appendString:btn.titleLabel.text];
    //把所有的输入拼接起来，得到一个完整的多位数字
    self.num1=[self.result doubleValue];//转成
    
    //这里是取到父视图，通过tag取到label，但是注意一点，，通过tag取到的是视图对象，这里先强制类型转换一下，然后用uilabel对象接收，这样就可以操作者的label对象
    
    UILabel *l=(UILabel*)[self viewWithTag:1000];
    l.text=self.result;
}
-(void)clearNum
{
    //清除按钮
    [self.result setString:@"0"];
    self.num1=0;
    self.num2=0;
    a=0;
    UILabel *l=(UILabel*)[self viewWithTag:1000];
    l.text=self.result;
}
//运算符 按钮
-(void)myOption:(UIButton*)btn
{
    //这里遇到一个问题，就是在判断中用的是char类型，而按钮的text是string类型，需要先转换一下
    const char *options=[btn.titleLabel.text UTF8String];
    char option=options[0];
    //在网上搜到这个，转utf8，转换成char字符串，然后再取到第一个。为什么不能直接转？因为他们的编码方式不同，转换之后就不是想要的字符串了
    //NSLog(@"%c",option);
    //这里就用到工厂来创建对象了，oper是父类的对象，但是根据运算符的不同实例化出来子类对象
    oper=[OperationFactory creatOpration:option];
    [self OptionResult];
    self.num2=[self.result doubleValue];
    [self.result setString:@""];//每次都置空一下，为了下一次的字符输入
    
}
//= 按钮
-(void)OptionResult
{
    if (a== 0 && self.num2 == 0) {
        return;
    }
    if (a!=0&&self.num2==0) {
        self.num2=a;
        //判断如果运算完之后继续运算的话，用之前的结果当做第一个数
    }
    //为运算类的两个数赋值
    oper.number1=self.num2;
    oper.number2=self.num1;
    //NSLog(@"%d",oper.number2);
    [self.result setString:[oper getResult]];//执行运算方法
    [self ClearZero];
    UILabel *l=(UILabel*)[self viewWithTag:1000];
    l.text=self.result;
    a=[self.result doubleValue];//接收运算结果
//    [self.result setString:@""];
    self.num2=0;
    //置空，为下一下次输入准备
}
-(void)ClearZero
{
    for (int i=[self.result length]-1; i>=0; i--) {
        char c=[self.result characterAtIndex:i];
        switch (c) {
            case '0':
                [self.result deleteCharactersInRange:NSMakeRange(i, 1)];
                break;
            case '.':
                [self.result deleteCharactersInRange:NSMakeRange(i, 1)];
                goto end;
                break;
            default:
                goto end;
                break;
        }
    }
end:;
}

- (void)change1:(UIButton *)button {
    UILabel *label = (UILabel *)[self viewWithTag:button.tag];
    NSLog(@"%ld",button.tag);
    NSLog(@"%ld",label.tag);
    button.tag += 1;
    label.tag = button.tag;
    NSLog(@"%ld",button.tag);
    NSLog(@"%ld",label.tag);
    int i = button.tag % 2;
    if (i == 1) {
        button.layer.borderColor = [[UIColor redColor] CGColor];
        if (button.tag < 6600) {
            self.costModel.name = @"加油费";
            UIImage *image = [UIImage imageNamed:@"Money0.png"];
            self.costModel.imagedata = UIImagePNGRepresentation(image);
        }
        if (button.tag > 6600 && button.tag < 12600 ) {
            self.costModel.name = @"保养费";
            UIImage *image = [UIImage imageNamed:@"Money1.png"];
            self.costModel.imagedata = UIImagePNGRepresentation(image);
        }
        if (button.tag > 12600) {
            self.costModel.name = @"过路费";
            UIImage *image = [UIImage imageNamed:@"Money2.png"];
            self.costModel.imagedata = UIImagePNGRepresentation(image);
        }
    }else {
        button.layer.borderColor = [kBackGroundColor CGColor];
    }
    self.button10 = button;
}

- (void)saveMoney {
    UILabel *l = (UILabel *)[self viewWithTag:1000];
    if (![self.result isEqualToString:@"0"] && ![l.text isEqualToString:@"¥0.00"] && self.costModel.name.length != 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSString *string = [formatter stringFromDate:[NSDate date]];
        self.costModel.date = string;
        NSLog(@"%@",self.costModel.date);
        self.costModel.money = self.result;
        NSLog(@"%@",self.costModel.money);
        [[CostDataBase sharedCost] insertModel:self.costModel];
        
    }
    l.text = @"¥0.00";
    [self.result setString:@""];
    self.costModel.name = @"";
    self.button10.layer.borderColor = [kBackGroundColor CGColor];
}














@end
